<template>
  <el-container class="layout-ltb">
    <el-container>
      <el-header height="114">
        <el-form
          ref="queryFormRef"
          :model="queryParams"
          size="small"
          label-position="right"
          class="search-form mt-[20px]"
        >
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="类型" prop="PlanSetType">
                <el-select
                  placeholder="请选择计划类型"
                  v-model="queryParams.PlanSetType"
                >
                  <el-option label="日计划" value="1" />
                  <el-option label="周计划" value="2" />
                  <el-option label="月计划" value="3" />
                  <el-option label="季计划" value="4" />
                  <el-option label="年计划" value="5" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向" prop="TaskType">
                <el-select
                  placeholder="请选择按区域/路线巡检"
                  v-model="queryParams.TaskType"
                >
                  <el-option label="按路线巡检" :value="1 * 1" />
                  <el-option label="按区域巡检" :value="2 * 1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="路线" prop="InspDestId">
                <el-select
                  :placeholder="
                    queryParams.TaskType == 1
                      ? '请选择路线'
                      : !queryParams.TaskType
                        ? '请选择'
                        : '请选择区域'
                  "
                  v-model="queryParams.InspDestId"
                >
                  <template v-for="item in lineData">
                    <el-option
                      :label="item.inspLineName"
                      :value="item.inspLineId"
                      :key="item.inspLineId"
                      v-if="queryParams.TaskType == item.inspLineType"
                    />
                  </template>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="完成时间" prop="InspDestId">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  append-to-body="false"
                  :clearable="false"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="部门" prop="InspDepartmentId">
                <el-select
                  placeholder="请选择巡检部门"
                  v-model="queryParams.InspDepartmentId"
                  @change="f_ChangeDep"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in depData"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="人员" prop="InspUserId">
                <el-select
                  placeholder="请选择巡检人员"
                  v-model="queryParams.InspUserId"
                >
                  <el-option
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                    v-for="item in operatorData"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="搜索" prop="KeyWords">
                <el-input
                  v-model="queryParams.KeyWords"
                  placeholder="请输入巡检名称/路线名称/姓名搜索"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button
                @click="f_HandleSearch"
                type="primary"
                class="btn-search"
                size="small"
              >
                <i-ep-search class="mr-[2px] text-size-[11px] v-bottom" />搜索
              </el-button>
              <el-button
                @click="f_HandleReset"
                type="warning"
                class="btn-reset"
              >
                <i-ep-refresh class="mr-[2px] text-size-[11px] v-bottom" />重置
              </el-button>
              <el-button
                @click="f_HandleExport"
                type=""
                class="btn-search"
                size="small"
              >
                <i-ep-download class="mr-[2px] text-size-[11px] v-bottom" />导出
              </el-button>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="20">
          <el-col :span="6" />
        </el-row>
      </el-header>
      <el-main>
        <div>
          <el-table
            :data="tableData"
            border
            :height="tableHeight"
            header-row-class-name="table-header"
            size="small"
          >
            <el-table-column
              type="index"
              width="60"
              label="序号"
              align="center"
            />
            <el-table-column
              prop="planSetName"
              label="巡检计划名称"
              align="center"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column prop="planSetType" label="计划类型" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.planSetType == 1" type="primary"
                  >日计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 2" type="success"
                  >周计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 3" type="info"
                  >月计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 4" type="warning"
                  >季计划</el-tag
                >
                <el-tag v-if="scope.row.planSetType == 5" type="danger"
                  >年计划</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="taskType"
              label="巡检方向"
              align="center"
              min-width="150"
            >
              <template #default="scope">
                <el-tag v-if="scope.row.taskType == 1" type="primary"
                  >线路</el-tag
                >
                <el-tag v-if="scope.row.taskType == 2" type="success"
                  >区域</el-tag
                >
                <el-tag v-if="scope.row.taskType == 0" type="success">-</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="inspDestName"
              label="线路/区域"
              align="center"
              min-width="150"
            />
            <el-table-column
              prop="taskName"
              label="巡检内容"
              align="center"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              prop="inspDeppartmentName"
              label="巡检部门"
              align="center"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              prop="inspUserName"
              label="巡检人"
              align="center"
              show-overflow-tooltip
              width="180"
            />
            <el-table-column
              prop="beginTime"
              label="开始巡检时间"
              align="center"
              width="150"
            />
            <el-table-column
              prop="doneTime"
              label="完成巡检时间"
              align="center"
              width="150"
            />
            <el-table-column
              prop="isAvoidHoliday"
              label="避开节假日"
              align="center"
              width="120"
            >
              <template #default="scope">
                <span v-if="scope.row.isAvoidHoliday">避开</span>

                <span v-else style="color: red">不避开</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="是否完成"
              align="center"
              width="120"
            >
              <template #default="scope">
                <!-- 任务状态 1-巡检中 2-已完成 3-已暂停 4-系统自动完成 -->
                <span v-if="scope.row.status == 1">巡检中</span>
                <span v-if="scope.row.status == 2">已完成</span>
                <span v-if="scope.row.status == 3">已暂停</span>
                <span v-if="scope.row.status == 4">系统自动完成</span>
                <span v-if="scope.row.status == 0">待处理</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="dangerCount"
              label="是否存在隐患"
              align="center"
              width="120"
            >
              <template #default="scope">
                <span v-if="scope.row.dangerCount" style="color: red">是</span>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="inspDuration"
              label="巡检时长"
              align="center"
            >
              <template #default="scope">
                {{ scope.row.inspDuration ? scope.row.inspDuration + "h" : "" }}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="200"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  @click="f_OpenDialog(scope.row)"
                  type="primary"
                  size="small"
                  link
                  ><i-ep-view
                    class="mr-[2px] text-size-[11px] v-bottom"
                  />查看详情</el-button
                >

                <el-button
                  v-if="scope.row.status != 0 && scope.row.beginTime"
                  @click="f_OpenDialogPerson(scope.row)"
                  type="danger"
                  size="small"
                  link
                  ><i-ep-place
                    class="mr-[2px] text-size-[11px] v-bottom"
                  />巡检轨迹</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <noneData :noneShow="!tableData.length" :height="tableHeight" />
          <pagination
            size="small"
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageIndex"
            v-model:limit="queryParams.pageSize"
            @pagination="f_HandelQuery"
          />
        </div>
      </el-main>
    </el-container>

    <!-- 弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      title="巡检计划"
      size="1400"
      append-to-body
      @close="f_CloseDialog"
      class="bg-[#f5f5f5!important]"
      destroy-on-close
    >
      <edit_drawer
        :form="form"
        :point-data="pointData"
        :task-data="taskData"
        @close="f_CloseDialog"
      />
    </el-drawer>

    <!-- 弹窗 -->
    <el-drawer
      v-model="dialogPerson.visible"
      title="巡检轨迹"
      size="90%"
      append-to-body
      @close="f_CloseDialog"
      class="bg-[#f5f5f5!important]"
      destroy-on-close
    >
      <person_drawer
        :form="form"
        :task-data="taskData"
        @close="f_CloseDialog"
      />
    </el-drawer>
  </el-container>
</template>

<script setup lang="ts">
defineOptions({
  name: "Inspection",
  inheritAttrs: false,
});
import DashboardAPI from "@/api/DashboardAPI";
import GisPointInfoAPI from "@/api/GisPointInfoAPI";
import moment from "moment";
import LineAPI from "@/api/LineAPI";
import GisPolygonInfoAPI from "@/api/GisPolygonInfoAPI";
import TaskSetAPI from "@/api/TaskSetAPI";
import TaskAPI from "@/api/TaskAPI";
import PlanAPI from "@/api/PlanAPI";
import edit_drawer from "./detail.vue";
import person_drawer from "./personmap/index.vue";
let tableHeight = ref(0);
// 弹窗对象
const dialog = reactive({
  visible: false,
  title: "",
});
// 弹窗对象
const dialogPerson = reactive({
  visible: false,
  title: "",
});
const dateRange = ref("");
const lineData = ref([]);
const queryFormRef = ref(ElForm);
const depData = ref([]);
const operatorData = ref([]);
const loading = ref(false);
const total = ref(0);
const tableData = ref([]);
const taskData = ref([]);
const polygonData = ref([]);
const form = ref({});
const pointData = ref([]);
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  PlanSetType: undefined,
  TaskSetType: undefined,
  InspDestId: undefined,
  InspDepartmentId: undefined,
  InspUserId: undefined,
  KeyWords: undefined,
});

//导出
function f_HandleExport() {
  if (dateRange.value && dateRange.value.length) {
    queryParams.StartTime = moment(dateRange.value[0]).format(
      "yyyy-MM-DD 00:00:00"
    );
    queryParams.EndTime = moment(dateRange.value[1]).format(
      "yyyy-MM-DD 23:59:59"
    );
  } else {
    delete queryParams.StartTime;
    delete queryParams.EndTime;
  }
  DashboardAPI.api_export_insp_task_export(queryParams).then((response) => {
    if (response) {
      const aLink = document.createElement("a");
      let blob = new Blob([response], {
        type: "application/vnd.ms-excel",
      });
      aLink.href = URL.createObjectURL(blob);
      aLink.setAttribute(
        "download",
        "巡检明细" +
          moment(new Date()).format("YYYY年MM月DD日HH时mm分ss秒") +
          ".xlsx"
      ); // 设置下载文件名称
      aLink.click();
      //使用后，需销毁
      URL.revokeObjectURL(aLink.href);
    } else {
      ElMessage({
        showClose: false,
        message: "数据加载失败！",
        type: "error",
      });
    }
  });
}

// 重置
function f_HandleReset() {
  queryFormRef.value.resetFields();
  dateRange.value = "";
  f_HandleSearch();
}

// 查询 管点
function f_HandleQueryPointLine() {
  let params = {
    pageSize: 10000,
    pageIndex: 1,
    isCoordinate: true,
  };
  GisPointInfoAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      pointData.value = data.items;
    }
  });
}

// 复制
function f_HandleStop(data: any) {
  ElMessageBox.confirm("确认暂停或启用?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    if (data.status != 1) {
      PlanAPI.api_enable(data.planSetId).then(({ data, succeeded }) => {
        if (succeeded) {
          ElMessage.success("操作成功！");
          f_HandelQuery();
        }
      });
    } else {
      PlanAPI.api_stop(data.planSetId).then(({ data, succeeded }) => {
        if (succeeded) {
          ElMessage.success("操作成功！");
          f_HandelQuery();
        }
      });
    }
  });
}

// 删除
function f_HandleDel(data: any) {
  ElMessageBox.confirm("确认删除数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      loading.value = true;
      PlanAPI.api_del(data.planSetId).then(({ data, errors, succeeded }) => {
        if (succeeded) {
          ElMessage.success("删除成功！");
          f_HandelQuery();
        }
        loading.value = false;
      });
    })
    .catch(() => ElMessage.info("已取消删除!"));
}

// 查询 路线
function f_HandelQueryLine() {
  let params = {
    pageSize: 100,
    pageIndex: 1,
  };
  LineAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      lineData.value = data.items;
    }
  });
}

// 打开弹窗
function f_OpenDialog(data: any) {
  form.value = data;
  dialog.visible = true;
}

// 打开弹窗
function f_OpenDialogPerson(data: any) {
  form.value = data;
  dialogPerson.visible = true;
}

// 搜索
function f_HandleSearch() {
  queryParams.pageIndex = 1;
  f_HandelQuery();
}

// 查询
function f_HandelQuery() {
  loading.value = true;
  if (dateRange.value && dateRange.value.length) {
    queryParams.StartTime = moment(dateRange.value[0]).format(
      "yyyy-MM-DD 00:00:00"
    );
    queryParams.EndTime = moment(dateRange.value[1]).format(
      "yyyy-MM-DD 23:59:59"
    );
  } else {
    delete queryParams.StartTime;
    delete queryParams.EndTime;
  }
  TaskAPI.api_query(queryParams).then(({ data, succeeded }) => {
    if (succeeded) {
      tableData.value = data.items;
      total.value = data.totalCount;
    }
  });
}

// 查询 任务
function f_HandelQueryTask() {
  let params = {
    pageIndex: 1,
    pageSize: 100,
  };
  TaskSetAPI.api_query(params).then(({ data, succeeded }) => {
    if (succeeded) {
      taskData.value = data.items;
    }
  });
}

// 查询 区域
function f_HandelQueryPolygon() {
  let params = {
    pageSize: 100,
    pageIndex: 1,
  };
  GisPolygonInfoAPI.api_query_geo(params).then(({ data, succeeded }) => {
    if (succeeded) {
      polygonData.value = data.items;
    }
  });
}

// 查询 部门
function f_HandelQueryDep() {
  TaskSetAPI.api_query_dep().then(({ data, succeeded }) => {
    if (succeeded) {
      depData.value = data;
    }
  });
}

// 部门 change
function f_ChangeDep() {
  let params = {
    DepartmentId: queryParams.InspDepartmentId,
  };
  TaskSetAPI.api_query_operators(params).then(({ data, succeeded }) => {
    if (succeeded) {
      operatorData.value = data;
    }
  });
}

// 关闭弹框
function f_CloseDialog() {
  dialog.visible = false;
  dialogPerson.visible = false;
  // queryParams.pageIndex = 1;
  // f_HandelQuery();
}

window.onresize = () => {
  return (() => {
    tableHeight.value = window.innerHeight - 320;
  })();
};

onMounted(() => {
  f_HandelQuery();
  f_HandelQueryTask();
  f_HandelQueryDep();
  f_HandelQueryPolygon();
  f_HandelQueryLine();
  f_HandleQueryPointLine();
  tableHeight.value = window.innerHeight - 320;
});
</script>
<style scoped lang="scss">
.mydrawer {
  background: red !important;
}
</style>
